<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 19-1-12 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace common\models;

use Yii;

/**
 * 用户注册表单
 * Register form
 */
class RegisterForm extends BaseModel
{
    const AGREEMENT_YES = 1;

    public $mobile;                 // 手机号
    public $countryCode = 86;       // 手机号国家代码: 86(中国)
    public $nickname;               // 用户昵称
    public $password;               // 登录密码
    public $confirmPassword;        // 确认密码
    public $captcha;                // 验证码
    public $captchaType;            // 验证码类型 none无，local系统验证码，sms短信
    public $agreement;              // 同意注册协议

    public $group = 0; // 管理员组1 普通用户0

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['password', 'confirmPassword', 'nickname', 'mobile'], 'trim'],
            ['agreement', 'default', 'value' => static::AGREEMENT_YES],
            [['password', 'confirmPassword', 'captcha', 'captchaType'], 'required'],
            [['username','nickname'], 'string', 'length' => [2, 20]],
            ['captchaType', 'in', 'range' => ['none', 'local', 'sms']],
            ['captcha', 'validateCaptcha'],
            ['mobile', 'validateMobile'],
            ['password', 'validatePassword'],
            [['password', 'confirmPassword'], 'string', 'min' => 8, 'max' => 20],
            ['confirmPassword', 'compare', 'compareAttribute' => 'password', 'message' => Yii::t('common', 'Password is not the same as the input.')],
            ['agreement', 'compare', 'compareValue' => static::AGREEMENT_YES, 'message' => Yii::t('common', 'Must agree to the membership agreement.')],
            ['nickname', 'unique', 'skipOnError' => true, 'targetClass' => '\common\models\User', 'targetAttribute' => 'nickname', 'message' => Yii::t('common', 'This nickname has already been taken.')],
        ];
    }

    /**
     * 验证码检测
     * Validates the captcha.
     * This method serves as the inline validation for captcha.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptcha($attribute, $params)
    {
        if (!$this->hasErrors() && (boolean) Yii::$app->config->getItem('userRegisterOnValidateCaptcha') === true) {
            if ($this->captchaType === 'local') {
                // 使用本地系统验证码
                if (!Yii::$app->controller->createAction('captcha')->validate(Yii::$app->request->post('captcha'), Yii::$app->config->getSiteItem('captchaCaseSensitive'))) {
                    $this->addError($attribute, '图形验证码不正确');
                }
            } else {
                // 使用短信验证码
                if (!Yii::$app->sms->validateCaptcha($this->$attribute, $params['mobile'], SmsCaptchaForm::LABEL_REGISTER)) {
                    $this->addError($attribute, '短信验证码不正确');
                }
            }
        }
    }

    /**
     * 手机号检测
     */
    public function validateMobile($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if (!Yii::$app->util->regExp($this->$attribute, 'cn_mobile')) {
                $this->addError($attribute, '手机号格式不正确');
            } else if (User::findByMobile($this->countryCode, $this->$attribute)) {
                $this->addError($attribute, '此手机号已被注册，请更换');
            }
        }
    }

    /**
     * 密码检测
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if (!Yii::$app->util->regExp($this->$attribute, 'password_power')) {
                $this->addError($attribute, '密码必须包含大小写字母和数字,长度8-20');
            }
        }
    }

    /**
     * 注册
     * @param int $id 自定义id
     * @return bool
     * @throws \yii\base\Exception
     */
    public function register($id = 0)
    {
        $user = new User();
        if ($id) {
            $user->id = (int) $id;
        }
        $user->nickname = $this->mobile;
        $user->group_id = $this->group;
        $user->mobile = $this->mobile;
        $user->access_token = $this->countryCode . $this->mobile;
        $user->country_code = $this->countryCode;
        $user->created_at = $user->updated_at = date('Y-m-d H:i:s');
        $user->setPassword(sha1($this->password));
        $userExtend = new UserExtend();
        $transaction  = Yii::$app->getDb()->beginTransaction();

        try {
            $user->save(false);
            // 扩展表
            $userExtend->uid = $user->id;
            $userExtend->created_at = $userExtend->updated_at = $user->created_at;

            if ($userExtend->save(false)) {
                $transaction->commit();
                return true;
            }
            $transaction->rollBack();
        } catch(\Exception $e) {
            $transaction->rollBack();
        }
        return false;
    }
}
